package com.rw.coco.data.data.mapper;

import com.rw.coco.api.data.model.BotModel;
import com.rw.coco.api.data.persistence.simple.SimpleBotMapper;
import com.rw.coco.data.data.bean.FileBotModel;
import com.rw.coco.data.data.util.BeanUtil;
import com.rw.tool.util.io.FileIOUtil;
import com.rw.tool.util.io.file.BeanFile;
import com.rw.tool.util.json.JsonUtil;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class FileBotMapper extends SimpleBotMapper {
    private static final String BOT_PATH = "\\bot\\";

    private final BeanFile<FileBotModel> beanFile;

    public FileBotMapper(String workPath) {
        File file = new File(workPath, BOT_PATH);
        FileIOUtil.mkDirs(file);
        this.beanFile = new BeanFile<>(file, FileBotModel.class);
    }

    private FileBotModel convert(BotModel data) {
        return JsonUtil.convertObj(data, FileBotModel.class);
    }

    private BotModel reconvert(FileBotModel data) {
        return JsonUtil.convertObj(data, BotModel.class);
    }

    private FileBotModel removeId(FileBotModel data) {
        return BeanUtil.removeIdProp(data, FileBotModel.class);
    }

    @Override
    public void insert(BotModel data) {
        beanFile.insert(convert(data));
    }

    @Override
    public void insertAll(Collection<BotModel> dataList) {
        List<FileBotModel> modelList = dataList.stream()
                .map(this::convert)
                .collect(Collectors.toList());

        beanFile.insertAll(modelList);
    }

    @Override
    public void delete(Serializable id) {
        beanFile.deleteById(id);
    }

    @Override
    public void deleteAll(BotModel data) {
        beanFile.delete(BeanUtil.getQueryWrapper(data));
    }

    @Override
    public void update(BotModel data) {
        FileBotModel botModel = convert(data);
        beanFile.update(BeanUtil.getIdWrapper(botModel), removeId(botModel));
    }

    @Override
    public BotModel selectOne(Serializable id) {
        return beanFile.selectById(id);
    }

    @Override
    public List<BotModel> selectList(BotModel data) {
        return beanFile.selectList(BeanUtil.getQueryWrapper(data))
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }

    @Override
    public List<BotModel> selectList(Collection<? extends Serializable> id) {
        return beanFile.selectList(id)
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }
}
